#ifndef UPDATEUTIL_H
#define UPDATEUTIL_H

#include <QTimer>
#include "downloader.h"
#include "softwarescan.h"
#include <QNetworkReply>

namespace ns_yht
{

#define UPDATEUTIL UpdateUtil::instance()

    class /*UPDATEUTIL_EXPORT*/ UpdateUtil : public QObject
    {
        Q_OBJECT

    public:
        UpdateUtil(const QVector<QPair<QString, QString>> &softwareList, const QString &appDir, bool needLoop = false);
        ~UpdateUtil();

        static UpdateUtil *instance();

        void startScan();
        SoftwareScan *getAppScan();
        // SoftwareScan *getBaseDataScan();

        bool needUpdate() const;
        // const QString &updateContent() const;

        void updateAll();
        QString getDownloadingFileName() const;

        // bool updateAppFromLocalFile(const QString &filename, const QString &destDir);

    private slots:
        void onScanFinished();

        void onDownloadFinished(bool isSucceed);
        void onDownloadProgress(qint64 a, qint64 b);

        void onUpdateLogFinished(QNetworkReply *reply);

    signals:
        void scanFinished();
        void downloadProgress(qint64 s);
        void downloadFinished();
        void updateFailed();
        void postlogFinished();

    private:
        /**
         * @brief resetFiles 更新失败，要将原来改为*.old 的文件还原
         */
        void resetFiles();
        void postUpdateLog(ModelSoftware *software, int result);

        QSharedPointer<SoftwareScan> appscan;
        // QSharedPointer<SoftwareScan> baseDatascan;

        static UpdateUtil *g_UpdateUtil;
        bool m_needLoop;
        QString m_appDir;

        QTimer *m_pTimer{nullptr};
        QSharedPointer<ModelSoftware> m_downloadingModel; // 当前正在下载的软件

        QScopedPointer<Downloader> m_downloder;
    };

}
#endif // UPDATEUTIL_H
